//
//  ByUIAddAddressVC.m
//  oc_knowledge
//
//  Created by mc on 17/1/12.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByUIAddAddressVC.h"
//Other
#import "ByOtherCityPickerView.h"

//Api
#import "ByApiAddress.h"

//Cell
#import "ByCellAddAddress.h"

//View
#import "ByViewTextViewPlaceholder.h"
@interface ByUIAddAddressVC ()<UITableViewDelegate,UITableViewDataSource,ByOtherCityPickerVieDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ByOtherCityPickerView *cityView;
@property (nonatomic, strong) UISwitch *defaultSwitch;


@property (nonatomic, strong) NSArray *titlesAry;
@property (nonatomic, strong) NSArray *placeAry;
@property (nonatomic, strong) NSMutableDictionary *areaDic;
@end

@implementation ByUIAddAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.type == 0?@"新增地址":@"修改地址";
    [self addLeftBackBarButtonItem];
    [self addBYItemviews:@[@"保存"] mode:ByNavigationItemModeText position:ByNavigationItemPositionModeRight];
    [self initTableView];
    [self initCityView];
}

#pragma mark ---getter
-(NSArray *)titlesAry{
    if (_titlesAry == nil) {
        _titlesAry = @[@"收货人",@"手机号码",@"选择地区"];
    }
    return _titlesAry;
}

-(NSArray *)placeAry{
    if (_placeAry == nil) {
        _placeAry = @[@"收货人的姓名",@"11位手机号",@"所在地区",@"请填写您的详细地址"];
        
    }
    return _placeAry;
}

-(UISwitch *)defaultSwitch{
    
    if (!_defaultSwitch) {
        _defaultSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 40, 20)];
        if ([self.alertModel.is_default isEqualToString:@"1"]) {
            [_defaultSwitch setOn:YES];
        }else{
            [_defaultSwitch setOn:NO];
        }
        
    }
    return _defaultSwitch;
}

-(NSMutableDictionary *)areaDic{
    if (_areaDic == nil) {
        _areaDic = [NSMutableDictionary dictionary];
    }
    return _areaDic;
}

#pragma mark ---创建视图
-(void)initTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    
}

/***创建城市选择器*/
- (void)initCityView{
    self.cityView = [[ByOtherCityPickerView alloc] initWithPicker];
    self.cityView.delegate = self;
    [self.view addSubview:self.cityView];
}

#pragma mark ----UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    /**新增地址*/
    if (self.type == 0) {
        return 2;
    }
    /**修改地址 且是默认地址*/
    else if([self.alertModel.is_default isEqualToString:@"1"]){
        return 2;

    }
    /**修改地址 且不是默认地址*/
    else
        return 3;


}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        ByCellAddAddress *cell = [ByCellAddAddress cellWithTableView:tableView andTitles:self.titlesAry andPlaceHolder:self.placeAry andType:self.type];
        if (self.alertModel != nil) {
            cell.model = self.alertModel;
        }
        cell.areaSelect = ^{
            [self areaClickAction];
        };
        cell.begainEdit = ^{
            [_cityView close];
        };
        return cell;
    }
    else{
        static NSString *indentier = @"addressCustomCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        /**新增地址*/
        if (self.type == 0) {
            cell.textLabel.text = @"设为默认地址";
            cell.accessoryView = self.defaultSwitch;
        }
        /**修改地址 且是默认地址*/
        else if ([self.alertModel.is_default isEqualToString:@"1"]){
            cell.textLabel.text = @"删除地址";
            cell.textLabel.textColor = [UIColor colorWithR:252 g:61 b:57];

        }
        /**修改地址 且不是默认地址*/
        else{
            if (indexPath.section == 1) {
                cell.textLabel.text = @"设为默认地址";
                cell.accessoryView = self.defaultSwitch;
            }else{
                cell.textLabel.text = @"删除地址";
                cell.textLabel.textColor = [UIColor colorWithR:252 g:61 b:57];
            }
        }
        return cell;

    }
  
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return self.titlesAry.count * 2 * 10 + self.titlesAry.count * 40 + 60;
    }
    else
        return 40;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.type == 1) {
        if ([self.alertModel.is_default isEqualToString:@"1"]) {
            /**删除地址*/
            if (indexPath.section == 1) {
                [self delAddress];
            }
        }else{
            if (indexPath.section == 2) {
                [self delAddress];
            }
        }
        
    }
}
#pragma mark ---删除地址
- (void)delAddress{
    [ByCoreToolAlert showLoadind:@"处理中..." hasMasker:YES];
    self.alertModel.s_id = BY_USER.s_id;
    self.alertModel.is_default = self.defaultSwitch.isOn == YES?@"1":@"0";
    [ByApiAddress addressDelete:self.alertModel success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showSuccessWithText:result.data];
        if (self.deleteAddress) {
            self.deleteAddress(self.alertModel);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}
#pragma mark ---保存
-(void)rightItemsAction:(NSInteger)rightIndex{

    //获取通用cell
    ByCellAddAddress *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    ByModelAddress *model = [[ByModelAddress alloc] init];
    UITextField *tf;UILabel *areaLabel;
    for (int i = 0; i < self.titlesAry.count; i ++) {
        if ([self.titlesAry[i] containsString:@"收货人"]) {
            tf = [cell viewWithTag:i + 10];
            model.contactname = tf.text;
        }
        if ([self.titlesAry[i] containsString:@"手机号"]) {
            tf = [cell viewWithTag:i + 10];
            model.mobile = tf.text;
        }
        if ([self.titlesAry[i] containsString:@"地区"]) {
            areaLabel = [cell viewWithTag:i + 10];
        }
    }
    if (self.areaDic.count != 0) {
        model.province = self.areaDic[@"province"];
        model.city = self.areaDic[@"city"];
        model.area = self.areaDic[@"area"];
    }
    else if (self.alertModel != nil){
        model.province = self.alertModel.province;
        model.city = self.alertModel.city;
        model.area = self.alertModel.area;
    }

    model.uid = BY_USER.uid;
    model.is_default = self.defaultSwitch.isOn == YES?@"1":@"0";
    model.s_id = BY_USER.s_id;
    ByViewTextViewPlaceholder *view = [cell viewWithTag:self.titlesAry.count + 10];
    model.detailinfo = view.text;
    
    NSString *area;
    if ([self.alertModel.city isEqualToString:@"市辖区"] || [self.alertModel.city isEqualToString:@"县"]) {
    area = [NSString stringWithFormat:@"%@%@",self.alertModel.province,self.alertModel.area];
    }else{
    area = [NSString stringWithFormat:@"%@%@%@",self.alertModel.province,self.alertModel.city,self.alertModel.area];
    }
    /**判断地址是否有修改  没有修改则不做任何操作*/
    if (self.alertModel != nil && [self.alertModel.contactname isEqualToString:model.contactname] && [self.alertModel.mobile isEqualToString: model.mobile]&&[areaLabel.text containsString:area] && (([self.alertModel.is_default isEqualToString:@"0"] && self.defaultSwitch.isOn == NO) || ([self.alertModel.is_default isEqualToString:@"1"] && self.defaultSwitch.isOn == YES))  && [self.alertModel.detailinfo isEqualToString:model.detailinfo]) {
        return;
    }
    /**新增地址*/
    if (self.type == 0) {
    [ByApiAddress addressAdd:model success:^(ByNetBaseResult *result) {
        model.address_id = result.data;
        if (self.addNewAddress) {
            self.addNewAddress(model);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
    }
    /**修改地址*/
    else{
    model.address_id = self.alertModel.address_id;
    [ByApiAddress addressUpdate:model success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showSuccessWithText:result.data];
        if (self.updateAddress) {
            self.updateAddress(model);
        }
        [self dismissViewControllerAnimated:YES completion:nil];

    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];

    }];
    }

}

#pragma mark ---地区选择代理
/**选择地区*/
- (void)areaClickAction{
    [_cityView open];
    /**获取地区label*/
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    ByCellAddAddress *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    UILabel *arealabel;
    for (int i = 0; i < self.titlesAry.count; i ++) {
        if ([self.titlesAry[i] containsString:@"地区"]) {
            arealabel = [cell viewWithTag:10 + i];
        }
    }
    arealabel.textColor = [UIColor blackColor];
    if (self.areaDic.count == 0) {
        [self.areaDic setObject:@"北京市" forKey:@"province"];
        [self.areaDic setObject:@"市辖区" forKey:@"city"];
        [self.areaDic setObject:@"东城区" forKey:@"area"];
        
        [self.areaDic setObject:@"11000" forKey:@"provinceid"];
        [self.areaDic setObject:@"110100" forKey:@"cityid"];
        [self.areaDic setObject:@"110101" forKey:@"areaid"];
        arealabel.text = @"北京市东城区";
    }

}

- (void)cityPickerViewDidChooseAddress:(ByOtherCityObject *)cityModel{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    ByCellAddAddress *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    UILabel *arealabel;
    for (int i = 0; i < self.titlesAry.count; i ++) {
        if ([self.titlesAry[i] containsString:@"地区"]) {
            arealabel = [cell viewWithTag:10 + i];
        }
    }
    
    arealabel.textColor = [UIColor blackColor];
    if ([cityModel.city isEqualToString:@"市辖区"] ||[cityModel.city isEqualToString:@"县"] ) {
        arealabel.text = [NSString stringWithFormat:@"%@%@",cityModel.province,cityModel.area];
    }else{
        arealabel.text = [NSString stringWithFormat:@"%@%@%@",cityModel.province,cityModel.city,cityModel.area];

    }
    
    [self.areaDic setObject:cityModel.province forKey:@"province"];
    [self.areaDic setObject:cityModel.city forKey:@"city"];
    [self.areaDic setObject:cityModel.area forKey:@"area"];
    [self.areaDic setObject:cityModel.provinceid forKey:@"provinceid"];
    [self.areaDic setObject:cityModel.cityid forKey:@"cityid"];
    [self.areaDic setObject:cityModel.areaid forKey:@"areaid"];
    
}


@end
